#pragma once
#include<iostream>
#include<pthread.h>
#include<string>
#include<unistd.h>
#include<cstring>
#include<functional>

#include "Log.hpp"
using namespace LogModule;

namespace MyThreadModule{

    static int sequence = 0;
    class Thread
    {
    private:
    void EnableRun()
    {
        printf("线程%s开始运行",_name.c_str());
        _isRun = true;   
    }
    void EnableDetach()
    {
        printf("线程%s分离了!!!\n",_name.c_str());
        _isDetach = true;
    }
        
    public:
        using func_t = std::function<void()>;
        Thread(func_t func)
        :_func(func)
        ,_tid(0)
        ,_isDetach(false)
        ,_isRun(false)
        ,_sequence(sequence++)
        {
            _name = "我是线程-" + std::to_string(sequence);
        }
        static void* routine(void* args) //如果不加static,参数一是this指针.
        {
            Thread* tmp = static_cast<Thread*>(args);
            tmp->_isRun = true;
            while(true)
            {
                //std::cout << tmp->_name << "运行中\n";
                tmp->_func(); //使用外部传入的函数.
                sleep(1);
            }
        }
        bool Start()
        {
            int ret = pthread_create(&_tid,nullptr,routine,this);
            //pthread_setname_np(_tid,_name.c_str());
            if(ret == 0)
            {
                LOG(LogLevel::DEBUG) << _name  << "Start 成功!!!" ;
            }
            else
            {
                printf("线程创建失败 , 错误码%s\n",strerror(ret));
                return false;
            }

            return true;
        }
        void Detach()
        {
            if(!_isDetach)
            {
                pthread_detach(_tid);
                EnableDetach();
            }
        }
        bool Stop()
        {
            if(_isRun)
            {
                int ret = pthread_cancel(_tid);
                if(ret == 0)
                {
                    LOG(LogLevel::DEBUG) << _name  << "Stop 成功!!!" ;
                }
                else
                {
                    std::cerr << "暂停失败,错误码:" << strerror(ret);
                }

            }
            return false;
        }
        void Join()
        {
            if(_isDetach)
            {
                std::cout << "线程已分离,无法join\n";
            }

            int ret = pthread_join(_tid,nullptr);
            if(ret != 0)
            {
                std::cout << "线程join失败\n";
            }
            else
            {
                LOG(LogLevel::DEBUG) << _name  << "Join 成功!!!" ;
            }
        }
        ~Thread()
        {}
    private:
        std::string _name;
        pthread_t _tid;
        bool _isDetach;
        bool _isRun;
        int _sequence;
        func_t _func;
    };


}